<template>
  <div>
    <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-width="120px">
      <el-form-item label="手机号码" prop="phone">
        <el-input type="phone" v-model.trim="ruleForm.phone" placeholder="请输入号码"
          onkeyup="value=value.replace(/[^\d]/g,'')" style="width: 280px;"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model.trim="ruleForm.name" placeholder="请输入姓名" style="width: 280px;"></el-input>
      </el-form-item>
      <el-form-item label="业务条线" prop="insuranceType">
        <el-select v-model="ruleForm.insuranceType" disabled placeholder="请选择业务条线" @change="changeLine" clearable
          style="width: 280px;">
          <el-option :label="item.dictLabel" :value="item.dictValue" v-for="item in bussinessOption"
            :key="item.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="获客平台" prop="customerSource">
        <el-select v-model="ruleForm.customerSource" placeholder="请选择获客平台" @change="changePlat" clearable
          style="width: 280px;">
          <el-option :label="item.scrmGetGuestPlatName" :value="item.scrmGetGuestPlatId" v-for="item in platformList"
            :key="item.scrmGetGuestPlatId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="获客来源" prop="customerWay">
        <el-select v-model="ruleForm.customerWay" placeholder="请选择获客来源" clearable style="width: 280px;">
          <el-option :label="item.scrmSourceName" :value="item.scrmGetGuestSourceId" v-for="item in sourceList"
            :key="item.scrmGetGuestSourceId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="weTagGroups">
        <tag-group v-model="ruleForm.weTagGroups" />
      </el-form-item>
      <el-form-item label="归属管理机构" v-if="!isMyCus">
        <mechanism-cascader :deptId.sync="ruleForm.departmentId" style="width: 280px;"></mechanism-cascader>
      </el-form-item>
      <el-form-item label="分配员工" v-if="!isMyCus" prop="weUserId">
        <el-select v-model="ruleForm.weUserId" placeholder="请选择员工" filterable clearable style="width: 280px;">
          <el-option :label="item.userName" :value="item.userId" v-for="item in weUserIds" :key="item.userId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="任务类型">
        <el-radio v-model="ruleForm.taskType" label="1">企微加好友</el-radio>
        <el-radio v-model="ruleForm.taskType" label="2">跟进</el-radio>
      </el-form-item>
      <el-form-item label="备注">
        <el-input type="textarea" placeholder="请添加备注" v-model="ruleForm.remark" maxlength="200" show-word-limit
          style="width: 280px;"></el-input>
      </el-form-item>
      <div class="foot">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="submitForm()">确定</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
import { getAllDepartment, getAllWeUser } from '@/api/customer/customerManage'
import mechanismCascader from '@/components/mechanismCascader.vue'
import { getPlat, getSource } from '@/api/sourceManage/sourceManage'
import MakeLabel from "@/components/MakeLabel/index.vue";
import { getInsuranceType } from '@/utils/auth'

export default {
  components: {
    mechanismCascader,
    MakeLabel
  },
  props: {
    isMyCus: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      ruleForm: {
        phone: '',
        name: '',
        insuranceType: null,
        customerSource: '',
        customerWay: '',
        weTagGroups: [],
        departmentId: null,
        weUserId: '',
        remark: '',
        taskType: ''
      },
      weTagGroups: [],
      organizationList: [],
      bussinessOption: [],
      platformList: [],
      sourceList: [],
      weUserIds: [],
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1\d{10}$/, message: '手机号格式错误', trigger: 'blur' }
        ],
        name: [
          { pattern: /^[\u4E00-\u9FA5A-Za-z]{2,}$/, message: '客户姓名至少为2个字', trigger: 'blur' }
        ],
        insuranceType: [
          { required: true, message: '请选择业务条线', trigger: 'change' }
        ],
        customerSource: [
          { required: true, message: '请选择获客平台', trigger: 'change' }
        ],
        customerWay: [
          { required: true, message: '请选择获客来源', trigger: 'change' }
        ],
      },

      makeLabelList: [],

      makeLabelVisible: false,

    }
  },
  created() {
    // this.getDepartmentInfo();
    this.getLabelList()
    this.ruleForm.insuranceType = getInsuranceType()
    this.changeLine()
  },
  watch: {
    'ruleForm.departmentId': {
      handler() {
        this.getAllWeUserInfo()
      }
    }
  },
  methods: {
    getLabelList() {
      // 业务条线
      // getLines().then((res) => {
      //     console.log(res, "----------------lines");
      //     const arr = [];
      //     res.rows.forEach(item => {
      //         arr.push(
      //             {
      //                 dictValue: item.scrmBussLineId,
      //                 dictLabel: item.scrmBussLineName
      //             }
      //         )
      //     });
      //     this.bussinessOption = arr;
      // });
      this.getDicts('insurance_type').then((res) => {
        if (res.code === 200) {
          this.bussinessOption = res.data
        }
      })
      //
      // getPlat().then((res) => {
      //   // 获客来源
      //   this.platformList = res.rows
      // })
    },
    // 改变业务条线
    changeLine() {
      if (this.ruleForm.insuranceType) {
        getPlat({ scrmBussLineId: this.ruleForm.insuranceType }).then((res) => {
          console.log(res, '----------------切换业务条线')
          this.platformList = res.rows || []
          this.ruleForm.customerSource = ''
          this.ruleForm.customerWay = ''
        })
      } else {
        this.platformList = []
        this.ruleForm.customerSource = ''
        this.ruleForm.customerWay = ''
      }

    },
    //改变业务平台
    changePlat() {
      if (this.ruleForm.customerSource) {
        getSource({ scrmGetGuestPlatId: this.ruleForm.customerSource }).then((res) => {
          // 获客来源
          this.sourceList = res.rows || []
          this.ruleForm.customerWay = ''
        })
      } else {
        this.sourceList = []
        this.ruleForm.customerWay = ''
      }
    },
    submitForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.addCustomer()
        } else {
          return false
        }
      })
    },
    resetForm() {
      this.$emit('closeCreatedDialog')
      this.ruleForm = {
        phone: '',
        name: '',
        insuranceType: getInsuranceType(),
        customerSource: '',
        customerWay: '',
        weTagGroups: [],
        weUserId: '',
        remark: '',
        departmentId: null,
        taskType: ''
      }
      this.$refs.ruleForm.resetFields();
      this.changeLine()
    },
    addCustomer() {
      let obj = JSON.parse(JSON.stringify(this.ruleForm))
      obj.weTagGroups = this.ruleForm.weTagGroups.map(item => {
        return {
          groupName: item.groupName,
          isMulti: item.isMulti,
          groupTagType: '1',
          weTags: [{ name: item.tagName }]
        }
      })
      this.$emit('sendCreateMessage', obj)
    },
    getDepartmentInfo() {
      getAllDepartment().then(res => {
        if (res.code === 200) {
          this.organizationList = res.data || []
          console.log(this.organizationList)
        }
      }).catch(() => {
        console.log('error submit!!')
      })
    },
    getAllWeUserInfo() {
      this.ruleForm.weUserId = ''
      const params = {
        department: this.ruleForm.departmentId,
        userName: ''
      }
      getAllWeUser(params).then(res => {
        if (res.code === 200) {
          this.weUserIds = res.data || []
        }
      }).catch(() => {
        console.log('error submit!!')
      })
    },
    //打开标签弹窗
    handleClickLabel() {
      this.makeLabelVisible = true
    },

    // 标签弹窗点击确定按钮
    makeLabelConfirm(value) {
      this.ruleForm.weTagGroups = value
      if (this.ruleForm.weTagGroups) {
        this.ruleForm.weTagGroups = this.ruleForm.weTagGroups.replace(
          /^\s*|\s*$/g,
          ''
        )
        if (
          this.ruleForm.weTagGroups.indexOf(';') != -1 ||
          this.ruleForm.weTagGroups.indexOf('；') != -1
        ) {
          let tagList = []
          let arr = this.ruleForm.weTagGroups.split(/[；;]/g)
          arr.forEach((item) => {
            item = String(item).replace(/^\s*|\s*$/g, '')
            if (tagList.indexOf(item) == -1 && item != '') {
              tagList.push(item)
            }
          })
          this.makeLabelList = tagList
        } else {
          let tagList = []
          tagList.push(this.ruleForm.weTagGroups)
          this.makeLabelList = tagList
        }
      }
    },

    // 关闭已经添加的标签
    handleCloseLabel(item) {
      this.makeLabelList = this.makeLabelList.filter((x) => {
        return x != item
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.foot {
  text-align: right;
}

.el-form-item:hover {
  border-radius: 10px;
  background: transparent;
}

.xiaozi {
  padding-left: 132px;
  color: #082aff;
}
</style>
